package com.vayne.thread;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author xuerui.zhang
 * @since 2020/4/26 下午2:17
 */
public class AtomicIntegerFieldUpdaterDemo implements Runnable {

    private static UpdateStudent tom;
    private static UpdateStudent jerry;

    private static final AtomicIntegerFieldUpdater<UpdateStudent> fieldUpdater =
            AtomicIntegerFieldUpdater.newUpdater(UpdateStudent.class, "score");

    public static class UpdateStudent {
        public volatile int score;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            tom.score++;
            fieldUpdater.getAndIncrement(jerry);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        tom = new UpdateStudent();
        jerry = new UpdateStudent();
        AtomicIntegerFieldUpdaterDemo updaterDemo = new AtomicIntegerFieldUpdaterDemo();
        Thread t1 = new Thread(updaterDemo);
        Thread t2 = new Thread(updaterDemo);
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println(tom.score);
        System.out.println(jerry.score);
    }
}
